package com.zmn.brs.admin.controller.ding.group.robot;

import com.zmn.brs.model.entity.robot.DingGroupRobot;
import com.zmn.brs.model.entity.robot.DingGroupRobotQuery;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


/**
 * 钉钉群机器人
 *
 * @author liuyong
 * @since 2021-08-02 11:41:35
 */
@Slf4j
@RestController
@RequestMapping("/ding/group/robot/")
public class DingGroupRobotModifyController extends DingGroupRobotBaseController {


    /**
     * 新增修改
     *
     * @param dingGroupRobot
     * @author liuyong
     * @since 2021-08-02 11:41:35
     */
    @RequestMapping(value = "addEdit")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody DingGroupRobot dingGroupRobot) {
        Date now = DateUtil.getNow();
        try {
            String operator = getMcStaffRealName();
            dingGroupRobot.setUpdater(operator);
            dingGroupRobot.setUpdateTime(now);
            DingGroupRobotQuery query = new DingGroupRobotQuery();
            query.setNotRobotId(dingGroupRobot.getRobotId());
            query.setGroupName(dingGroupRobot.getGroupName());
            DingGroupRobot robot = dingGroupRobotService.findByQuery(query);
            if (robot != null) {
                return ResponseDTO.fail("操作失败，钉钉群名称已经存在！");
            }
            if (NumberUtil.isNullOrZero(dingGroupRobot.getRobotId())) {
                dingGroupRobot.setCreater(operator);
                dingGroupRobot.setCreateTime(now);
                dingGroupRobotService.insert(dingGroupRobot);
            } else {
                dingGroupRobotService.updateByKey(dingGroupRobot);
            }
            return ResponseDTO.success(true, "操作成功！");
        } catch (Exception ex) {
            logger.error("[zmn]操作失败,钉钉群机器人:{}", dingGroupRobot, ex);
            return ResponseDTO.fail("操作失败！");
        }
    }


    /**
     * 查询全部
     *
     * @return
     */
    @RequestMapping("listAll")
    public ResponseDTO listAll() {
        List<DingGroupRobot> items = dingGroupRobotService.listByQuery(null);
        return ResponseDTO.success(items);
    }
}
